package com.xiaoxin.experience.service.storage;

import com.xiaoxin.experience.util.FileUtil;
import com.xiaoxin.experience.util.JSONUtil;
import com.xiaoxin.experience.util.StringUtil;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author xiaoxin
 */
public class JsonFileHandler
{
    public static <T> List<T> loadJson(String jsonFileName, Class<T> clazz)
    {
        byte[] bytes = FileUtil.readAllFileToBytes(jsonFileName);
        String json = new String(bytes, StandardCharsets.UTF_8);
        if (StringUtil.isBlank(json))
        {
            json = "[]";
        }
        return JSONUtil.jsonToList(json,clazz);
    }

    public static <T> void save(String path,List<T> objects)
    {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < objects.size(); i++)
        {
            sb.append(JSONUtil.toJson(objects.get(i)));
            if (i < objects.size() - 1)
            {
                sb.append(",\r\n");
            }
        }
        sb.append("]");
        FileUtil.writeToFile(sb.toString(),path,false);
    }
}
